package com.jsrj.common.utils;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JWTUtils {

    public static final String AUTH_HEADER_KEY = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer";

//    过期时间一周
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    private static final String secret = "jsrj_daolu";


    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            return false;
        }

    }

    /**
     * 获得token 中的信息无需secret解密也能获得
     * @param token
     * @return
     */
    public static String getUserId(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("openId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }

    }

    /***
     * 签发token
     * @param res 用户的openId  唯一的
     * @return
     */
    public static String sign(String res){

        System.out.println(res);  //输出 oTy_R5YVtXazKpAvmTaO9DBeFbiM

        JSONObject jsonObject = JSON.parseObject(res);
        String sessionKey = (String) jsonObject.get("session_key");
        String openId = (String) jsonObject.get("openid");

        try {
//            设置token 的失效时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);

            Algorithm algorithm = Algorithm.HMAC256(secret);
            String token = JWT.create()
                    .withClaim("sessionKey", sessionKey)
                    .withClaim("openId", openId)
                    .withExpiresAt(date)
                    .sign(algorithm);

            System.out.println("token密钥："+token);

            return token;
        } catch (UnsupportedEncodingException e) {
            return null;
        }


    }






}
